package com.tiger.project.service.impl;

import com.tiger.common.config.StandardConfig;
import com.tiger.common.utils.StringUtils;
import com.tiger.common.utils.WordGenerateUtil;
import com.tiger.common.utils.uuid.IdUtils;
import com.tiger.project.domain.ContractSponsor;
import com.tiger.project.domain.ReportInfo;
import com.tiger.project.mapper.ContractBillMapper;
import com.tiger.project.mapper.ContractSponsorMapper;
import com.tiger.project.mapper.ReportInfoMapper;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class ReportUtil {
    @Autowired
    private ContractSponsorMapper sponsorMapper;

    @Autowired
    private ReportInfoMapper reportInfoMapper;

    @Autowired
    private ContractBillMapper billMapper;


    //合同租赁
    @Async
    public void getReport1(Long id, Long deptId, String type) throws IOException {
        ContractSponsor sponsor = sponsorMapper.selectContractSponsorById(id);
        Map<String, Object> map = new HashMap<>();
        //合同信息
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        map.put("contractSponsorNo", sponsor.getContractSponsorNo());
        map.put("${lessorName}", sponsor.getLessorName());
        map.put("${lesseeName}",sponsor.getLesseeName());
        map.put("assetPlace",sponsor.getAssetPlace());
        map.put("${signTime}",sdf.format(sponsor.getSignTime()));
        map.put("signPlace",sponsor.getSignPlace());
        map.put("${rentArea}",sponsor.getRentArea().toPlainString());
        map.put("rentDuration",sponsor.getRentDuration());
        map.put("${rentStateTime}",sdf.format(sponsor.getRentStateTime()));
        map.put("${rentEndTime}",sdf.format(sponsor.getRentEndTime()));
        map.put("payee",sponsor.getPayee());
        map.put("${depositBank}",sponsor.getDepositBank());
        map.put("${bankAccount}",sponsor.getBankAccount());
        map.put("${rentUse}",sponsor.getRentUse());
        map.put("${cashPledge}",sponsor.getCashPledge().toPlainString());
        map.put("${firstParty}",sponsor.getFirstParty());
        map.put("${firstPartyAddress}",sponsor.getFirstPartyAddress());
        map.put("${firstPartyPhone}",sponsor.getFirstPartyPhone());
        map.put("${firstPartyEmali}",sponsor.getFirstPartyEmali());
        map.put("${firstPartyFax}",sponsor.getFirstPartyFax());
        map.put("${firstPartyQq}",sponsor.getFirstPartyQq());
        map.put("${firstPartyWechat}",sponsor.getFirstPartyWechat());
        map.put("${firstPartyPostalCode}",sponsor.getFirstPartyPostalCode());
        map.put("${secondParty}",sponsor.getSecondParty());
        map.put("${secondPartyAddress}",sponsor.getSecondPartyAddress());
        map.put("${secondPartyPhone}",sponsor.getSecondPartyPhone());
        map.put("${secondPartyEmali}",sponsor.getSecondPartyEmali());
        map.put("${secondPartyFax}",sponsor.getSecondPartyFax());
        map.put("${secondPartyQq}",sponsor.getSecondPartyQq());
        map.put("${secondPartyWechat}",sponsor.getSecondPartyWechat());
        map.put("${secondPartyPostalCode}",sponsor.getSecondPartyPostalCode());
        map.put("${rentRental}",sponsor.getRentRental().toPlainString());
        map.put("yearlyRent",sponsor.getYearlyRent().toPlainString());
        map.put("${propertyCertification}",sponsor.getPropertyCertification());
        map.put("${letWay}",sponsor.getLetWay());
        map.put("${propertyFeeSquare}",sponsor.getPropertyFeeSquare());

        //账单信息
        List<Map<String,Object>> list1 = billMapper.selectPatrolTermMap(id, deptId);

        map.put("tt",list1);


        //合同信息
//        List<Map<String, Object>> list = sponsorMapper.selectByMap(deptId, id);
//        map.put("${lessorName}",list.get(0).get("lessorName1"));
//        map.put("${lesseeName}",list.get(0).get("lesseeName1"));

        String fileName = null;
        if ("3".equals(type)) {
            fileName = "房屋租赁合同-城供.docx";
        }else if ("1".equals(type)){
            fileName = "国融资产运营平台.docx";
        }
        exportReport(map, fileName, type, deptId,id);

    }

    @Async
    public void getReport2(Long id, Long deptId, String type) throws IOException {
        ContractSponsor sponsor = sponsorMapper.selectContractSponsorById(id);
        Map<String, Object> map = new HashMap<>();
        //合同信息
        map.put("lessorName", sponsor.getLessorName());
        map.put("lesseeName",sponsor.getLesseeName());
        map.put("contractSponsorNo", sponsor.getContractSponsorNo());
        String fileName = null;
        if ("3".equals(type)) {
            fileName = "安全协议-城供.docx";
        }else if ("1".equals(type)){
            fileName = "国融资产运营平台安全责任书.docx";
        }
        exportReport1(map, fileName, type, deptId,id);

    }



    /**
     * @param map          数据
     * @param fileName     文件名称
     * @param type         文档类型
     * @param deptId     公司信息
     * @param
     * @throws IOException
     */
    @Async
    public void exportReport(Map<String, Object> map, String fileName, String type, Long deptId,Long id) throws IOException {
        String path = "";
        if ("3".equals(type)) {
            path = "房屋租赁合同-城供.docx";
        }else if ("1".equals(type)){
            path = "国融资产运营平台.docx";
        }
        String filePath = StandardConfig.getUploadPath();
        //获取模板流
        InputStream ins = this.getClass().getResourceAsStream("/report/" + path);
        // 公共组件变形
        XWPFDocument bStream = WordGenerateUtil.TemplateTransfer(ins, map);
        String url = "/report/" + LocalDate.now().getYear() + "/" + IdUtils.fastUUID() + "/" + fileName;
        getAbsoluteFile(filePath + url);
        //输出
        OutputStream os = new FileOutputStream(filePath + url);
        bStream.write(os);
        ins.close();
        os.close();

        ReportInfo reportInfo = new ReportInfo();
        reportInfo.setCompanyId(deptId);
        reportInfo.setReportName(fileName);
        reportInfo.setSysAddress("/profile/upload" + url);
        reportInfo.setType(type);
        reportInfo.setContractSponsorId(id);
        reportInfoMapper.insertReportInfo(reportInfo);


    }

    @Async
    public void exportReport1(Map<String, Object> map, String fileName, String type, Long deptId,Long id) throws IOException {
        String path = "";
        if ("3".equals(type)) {
            path = "安全协议-城供.docx";
        }else if ("1".equals(type)){
            path = "国融资产运营平台安全责任书.docx";
        }
        String filePath = StandardConfig.getUploadPath();
        //获取模板流
        InputStream ins = this.getClass().getResourceAsStream("/report/" + path);
        // 公共组件变形
        XWPFDocument bStream = WordGenerateUtil.TemplateTransfer(ins, map);
        String url = "/report/" + LocalDate.now().getYear() + "/" + IdUtils.fastUUID() + "/" + fileName;
        getAbsoluteFile(filePath + url);
        //输出
        OutputStream os = new FileOutputStream(filePath + url);
        bStream.write(os);
        ins.close();
        os.close();

        ReportInfo reportInfo = new ReportInfo();
        reportInfo.setCompanyId(deptId);
        reportInfo.setReportName(fileName);
        reportInfo.setSysAddress("/profile/upload" + url);
        reportInfo.setType(type);
        reportInfo.setContractSponsorId(id);
        reportInfoMapper.insertReportInfo(reportInfo);


    }


    public static final File getAbsoluteFile(String fileName) throws IOException {
        File desc = new File(fileName);
        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
        }
        return desc;
    }



    public static void main(String[] args) {
        String docPath = "C://Users//15285//Desktop//房屋租赁合同.docx";
        String pdfPath = "C://Users//15285//Desktop//房屋租赁合同.pdf";

        try {
            XWPFDocument document;
            InputStream doc = new FileInputStream(docPath);
            document = new XWPFDocument(doc);
            PdfOptions options = PdfOptions.create();
            OutputStream out = new FileOutputStream(pdfPath);
            PdfConverter.getInstance().convert(document, out, options);
            System.out.println("恭喜你终于word->pdf 转换成功了！");
            doc.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


}
